<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Teache;
class TeachController extends Controller
{
    //添加老师
    public function teach_add(Request $request,Teache $teache){
        if($request->isMethod('post')){
            if(empty($request->file('img'))){
                $file = '';
            }else{
                $file = $request->file('img')->store(date('Y-m-d'));
            }
            $data = $request->except('_token');
            $data['img'] = $file;
            $data['content'] = $data['editorValue'];
            //如果简介没有填写的话 自动从介绍中提取前五十个字作为简介
            if(empty($data['tell'])){
                $tell = strip_tags($data['editorValue']);
                $data['tell'] = mb_substr($tell, 0, 50, 'utf-8');
            }
            $result = $teache->create($data);
            if($result != false){
                session()->flash('success','添加成功');
                return redirect()->back();
            }else{
                session()->flash('success','添加失败');
                return redirect()->back();
            }
        }else{
            return view('Admin/Teach/teach_add');
        }
    }
    //老师列表
    public function teach_list(Teache $teache){
        $data = $teache->get();
        return view('Admin/Teach/teach_list',['data'=>$data]);
    }
    //老师idchakan
    public function teach_upd(Teache $teache,$id){
        $data = $teache->where('id',$id)->get();
        return view('Admin/Teach/teach_upd',['data'=>$data]);
    }
    //修改
    public function teach_update(Request $request,Teache $teache){
        $data = $request->except('_token');
        $where = ['id'=>$data['id']];
        if(!empty($data['editorValue'])){
            $re['content'] = $data['editorValue'];
        }
        if(!is_null($request->file('img'))){
            $re['img'] = $request->file('img')->store(date('Y-m-d'));
        }
        if(empty($data['tell'])){
            if(!empty($data['editorValue'])){
                $tell = strip_tags($data['editorValue']);
                $data['tell'] = mb_substr($tell, 0, 50, 'utf-8');
            }else{
                $new = $teache->where($where)->get()->toarray();
                $a['content'] = $new[0]['content'];
                $tell = strip_tags($a['content']);
                $data['tell'] = mb_substr($tell, 0, 50, 'utf-8');
            }
        }
        $re['name'] = $data['name'];
        $re['tell'] = $data['tell'];
        $result = $teache->where($where)->update($re);
        if($result != false){
            session()->flash('success','修改成功');
            return redirect()->back();
        }else{
            session()->flash('success','修改失败');
            return redirect()->back();
        }
    }
    //删除
    public function delete(Teache $teache,$id){
        $result = $teache->where('id',$id)->delete();
        return redirect()->back();
    }
}
